﻿using System.Text.RegularExpressions;
using System.Web.UI;
using System.Web.UI.Adapters;
using System.IO;

namespace HelpersDotNet.Web.ViewState
{
    /// <summary>
    /// Moves the view state to the bottom of the Page for SEO.
    /// </summary>
    /// <example>
    ///     <code>
    ///         <browsers>
    ///             <browser refID="Default">
    ///                 <controlAdapters>
    ///                     <adapter controlType="System.Web.UI.Page" adapterType="HelpersDotNet.Web.Adapters.MoveViewStatePageAdapter"/>
    ///                 </controlAdapters>
    ///             </browser>
    ///         </browsers> 
    ///     </code>
    /// </example>
    public class MoveViewStatePageAdapter : PageAdapter
    {
        protected override void Render(HtmlTextWriter writer)
        {
            using (StringWriter stringWriter = new StringWriter())
            {
                using (HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter))
                {
                    base.Render(htmlWriter);

                    string html = stringWriter.ToString();

                    int startPoint = html.IndexOf("<input type=\"hidden\" name=\"__VIEWSTATE\" id=\"__VIEWSTATE\"");

                    if (startPoint > 0)
                    {
                        int endPoint = html.IndexOf("/>", startPoint) + 2;

                        string viewStateInput = html.Substring(startPoint, endPoint - startPoint);
                        html = html.Remove(startPoint, endPoint - startPoint);

                        int formEndStart = html.IndexOf("</form>");
                        if (formEndStart >= 0)
                            html = html.Insert(formEndStart, viewStateInput);
                    }

                    writer.Write(html);
                }
            }
        }
    }
}
